package org.example;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.search.SubjectTerm;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Properties;

public class GetMailUtils {
    Logger log = LoggerFactory.getLogger(GetMailUtils.class);
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(final String[] args) throws MessagingException, IOException {

        final String server = "pop3.163.com";
        final String username = "";
        String password = "";
        // 创建一个新的邮件会话

        Properties props = new Properties();

        props.put("mail.pop3.auth", true);
        // TLS 需要这两行
        props.put("mail.pop3.starttls.enable", true);
        props.put("mail.pop3.port", "110");
        // SSL 需要这三行
//        props.put("mail.pop3.ssl.enable", true);
//        props.put("mail.pop3.port", "465");
//        props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.put("mail.pop3.host", "smtp.163.com");
        props.put("mail.pop3.host", server);

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        // 设置用于连接到邮件服务器的地址和凭证
        session.setDebug(true);
//        session.setHost("mail.example.com");
//        session.setUser("your_email@example.com");
//        session.setPassword("your_password");

        // 创建一个新的邮件存储区
        Store store = session.getStore();

        store.connect();

        // 获取要搜索的邮件
        Folder folder = store.getDefaultFolder();
        Message[] messages = folder.search(new SubjectTerm(""));

        // 遍历所有的邮件
        for (Message message : messages) {
            // 获取邮件内容
            String content = (String) message.getContent();

            // 输出邮件内容
            System.out.println(content);
        }

    }
}
